package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.domain.*;
import com.erp.gather.domain.bo.ErpSellerStoreProductBo;
import com.erp.gather.domain.vo.ErpSellerProductExpandVo;
import com.erp.gather.domain.vo.ErpSellerProductSkuVo;
import com.erp.gather.domain.vo.ErpSellerStoreProductExpandVo;
import com.erp.gather.domain.vo.ErpSellerStoreProductVo;
import com.erp.gather.mapper.*;
import com.erp.gather.service.IAeProductService;
import com.erp.gather.service.IErpProductPriceControlService;
import com.erp.gather.service.IErpSellerStoreProductGroupService;
import com.erp.gather.service.IErpSellerStoreProductService;
import com.esotericsoftware.minlog.Log;
import com.ruoyi.ae.api.RemoteAeProductService;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldDomain.BaseEntity;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.gather.api.domain.*;
import com.ruoyi.shop.api.RemoteSellerStoreFreightTemplateService;
import com.ruoyi.shop.api.RemoteSellerStorePriceTemplateService;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.shop.api.domain.ErpSellerStoreFreightTemplate;
import com.ruoyi.shop.api.domain.ErpSellerStorePriceTemplate;
import com.ruoyi.system.api.RemoteDictDataService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.map.LinkedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static jodd.util.ThreadUtil.sleep;

/**
 * 卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）Service业务层处理
 *
 * @author erp
 * @date 2023-03-28
 */
@RequiredArgsConstructor
@Service
public class ErpSellerStoreProductServiceImpl implements IErpSellerStoreProductService {
    @Autowired
    RestTemplate restTemplate;

    private final ErpSellerStoreProductMapper baseMapper;
    private final ErpSellerStoreProductSkuMapper erpSellerStoreProductSkuMapper;
    private final ErpSellerStoreProductExpandMapper erpSellerStoreProductExpandMapper;
    private final ErpCollectProductExpandMapper collectProductExpandMapper;
    private final ErpCollectProductMapper erpCollectProductMapper;
    private final ErpCollectProductSkuMapper erpCollectProductSkuMapper;
    private final IErpProductPriceControlService iErpProductPriceControlService;
    private final IAeProductService iAeProductService;

    private final ErpSellerProductMapper erpSellerProductMapper;
    private final ErpSellerProductSkuMapper erpSellerProductSkuMapper;
    private final ErpSellerProductExpandMapper erpSellerProductExpandMapper;
    private final ErpSellerStoreProductGroupMapper erpSellerStoreProductGroupMapper;
    private final AliexpressCategoryServiceImpl aliexpressCategoryServiceImpl;
    @Resource
    RemoteSellerStorePriceTemplateService remoteSellerStorePriceTemplateService;
    @Resource
    RemoteSellerStoreFreightTemplateService remoteSellerStoreFreightTemplateService;
    @Resource
    RemoteDictDataService remoteDictDataService;
    @Resource
    RemoteAeProductService remoteAeProductService;
    @Resource
    RemoteUserService remoteUserService;
    @Resource
    RemoteSellerStoreService remoteSellerStoreService;

    private final ErpSellerStoreEuResponsiblePersonMapper erpSellerStoreEuResponsiblePersonMapper;


    /**
     * 查询卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public ErpSellerStoreProductVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）列表
     */
    @Override
    public List<ErpSellerStoreProductVo> queryList(ErpSellerStoreProductBo bo) {
        LambdaQueryWrapper<ErpSellerStoreProduct> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSellerStoreProduct> buildQueryWrapper(ErpSellerStoreProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerStoreProduct> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getId() != null, ErpSellerStoreProduct::getId, bo.getId());
        lqw.eq(bo.getSellerProductId() != null, ErpSellerStoreProduct::getSellerProductId, bo.getSellerProductId());
        lqw.eq(bo.getCollectProductId() != null, ErpSellerStoreProduct::getCollectProductId, bo.getCollectProductId());
        lqw.eq(bo.getAeProductId() != null, ErpSellerStoreProduct::getAeProductId, bo.getAeProductId());
//		lqw.eq(bo.getStoreId() != null, ErpSellerStoreProduct::getStoreId, bo.getStoreId());
        lqw.eq(bo.getStoreUserName() != null, ErpSellerStoreProduct::getStoreUserName, bo.getStoreUserName());
        lqw.eq(bo.getCategoryId() != null, ErpSellerStoreProduct::getCategoryId, bo.getCategoryId());
        lqw.eq(StringUtils.isNotBlank(bo.getImageURLs()), ErpSellerStoreProduct::getImageURLs, bo.getImageURLs());
        lqw.like(StringUtils.isNotBlank(bo.getSubject()), ErpSellerStoreProduct::getSubject, bo.getSubject());
        lqw.eq(StringUtils.isNotBlank(bo.getWhite()), ErpSellerStoreProduct::getWhite, bo.getWhite());
        lqw.eq(StringUtils.isNotBlank(bo.getMarketing()), ErpSellerStoreProduct::getMarketing, bo.getMarketing());
        lqw.eq(StringUtils.isNotBlank(bo.getMedia()), ErpSellerStoreProduct::getMedia, bo.getMedia());
        lqw.eq(StringUtils.isNotBlank(bo.getProductPrice()), ErpSellerStoreProduct::getProductPrice,
                bo.getProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getMobileDetail()), ErpSellerStoreProduct::getMobileDetail,
                bo.getMobileDetail());
        lqw.eq(bo.getPackageLength() != null, ErpSellerStoreProduct::getPackageLength, bo.getPackageLength());
        lqw.eq(StringUtils.isNotBlank(bo.getPackageWidth()), ErpSellerStoreProduct::getPackageWidth,
                bo.getPackageWidth());
        lqw.eq(bo.getPackageHeight() != null, ErpSellerStoreProduct::getPackageHeight, bo.getPackageHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getGrossWeight()), ErpSellerStoreProduct::getGrossWeight, bo.getGrossWeight());
        lqw.eq(bo.getProductUnit() != null, ErpSellerStoreProduct::getProductUnit, bo.getProductUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomAttributes()), ErpSellerStoreProduct::getCustomAttributes,
                bo.getCustomAttributes());
        lqw.eq(StringUtils.isNotBlank(bo.getDetail()), ErpSellerStoreProduct::getDetail, bo.getDetail());
        lqw.eq(StringUtils.isNotBlank(bo.getDetailImg()), ErpSellerStoreProduct::getDetailImg, bo.getDetailImg());
        lqw.eq(bo.getSizechartId() != null, ErpSellerStoreProduct::getSizechartId, bo.getSizechartId());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectUrl()), ErpSellerStoreProduct::getCollectUrl, bo.getCollectUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerStoreProduct::getRevision, bo.getRevision());
//		// 商品状态
//		if (StringUtils.isNotEmpty(bo.getCollectProductStatus())) {
//			List<ErpSellerStoreProductExpandVo> expandVos = erpSellerStoreProductExpandMapper
//					.selectVoList(new LambdaQueryWrapper<ErpSellerStoreProductExpand>()
//							.eq(ErpSellerStoreProductExpand::getProductStatusType, bo.getCollectProductStatus()));
//			List<Long> sellerStoreProductIdList = new ArrayList<>();
//			expandVos.forEach(vo -> {
//				sellerStoreProductIdList.add(vo.getSellerStoreProductId());
//			});
//			if (sellerStoreProductIdList.size() > 0) {
//				lqw.in(ErpSellerStoreProduct::getId, sellerStoreProductIdList);
//			} else {
//				lqw.eq(ErpSellerStoreProduct::getId, "00001"); // 说明没有符合条件的
//			}
//		}
//		// 产品状态
//		if (StringUtils.isNotEmpty(bo.getProductStatusType())) {
//			List<ErpCollectProductExpandVo> collectProductExpandList = collectProductExpandMapper
//					.selectVoList(new LambdaQueryWrapper<ErpCollectProductExpand>()
//							.eq(ErpCollectProductExpand::getProductStatus, bo.getProductStatusType()));
//			List<Long> productStatusTypeList = new ArrayList<>();
//			collectProductExpandList.forEach(vo -> {
//				productStatusTypeList.add(vo.getCollectProductId());
//			});
//			if (productStatusTypeList.size() > 0) {
//				lqw.in(ErpSellerStoreProduct::getCollectProductId, productStatusTypeList);
//			} else {
//				lqw.eq(ErpSellerStoreProduct::getCollectProductId, "00001"); // 说明没有符合条件的
//			}
//		}

        // 当查找分组时用到
        String groupStatus = bo.getGroupStatus();
        if (StringUtils.isNotEmpty(groupStatus)) {
            if (groupStatus.equals("1")) {
                lqw.apply(
                        " id in (select seller_store_product_id from erp_seller_store_product_group where group_id = '"
                                + bo.getGroupId() + "'and status != -1) ");
            } else {
                lqw.apply(
                        " id not in (select seller_store_product_id from erp_seller_store_product_group where group_id = '"
                                + bo.getGroupId() + "' and status != -1) ");
            }
        }

        // 商品状态
        String collectProductStatus = bo.getCollectProductStatus();
        if (StringUtils.isNotEmpty(collectProductStatus)) {
            lqw.apply(
                    " id in (select seller_store_product_id from erp_seller_store_product_expand where product_status_type =  '"
                            + collectProductStatus + "')");
        }

        // 产品状态
        String productStatusType = bo.getProductStatusType();
        if (StringUtils.isNotEmpty(productStatusType)) {
            lqw.apply(
                    " collect_product_id in (select collect_product_id from erp_collect_product_expand where product_status =  '"
                            + productStatusType + "')");
        }
//		else {
//			lqw.eq(ErpSellerStoreProduct::getCollectProductId, "00001"); // 说明没有符合条件的
//		}

        lqw.orderByDesc(ErpSellerStoreProduct::getUpdateTime);
        return lqw;
    }

    private LambdaQueryWrapper<ErpSellerStoreProduct> buildQueryWrapperNew(ErpSellerStoreProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerStoreProduct> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getId() != null, ErpSellerStoreProduct::getId, bo.getId());
        lqw.eq(bo.getSellerProductId() != null, ErpSellerStoreProduct::getSellerProductId, bo.getSellerProductId());
        lqw.eq(bo.getCollectProductId() != null, ErpSellerStoreProduct::getCollectProductId, bo.getCollectProductId());
        lqw.eq(bo.getAeProductId() != null, ErpSellerStoreProduct::getAeProductId, bo.getAeProductId());
        lqw.eq(bo.getStoreId() != null, ErpSellerStoreProduct::getStoreId, bo.getStoreId());
        lqw.eq(bo.getStoreUserName() != null, ErpSellerStoreProduct::getStoreUserName, bo.getStoreUserName());
        lqw.eq(bo.getCategoryId() != null, ErpSellerStoreProduct::getCategoryId, bo.getCategoryId());
        lqw.eq(StringUtils.isNotBlank(bo.getImageURLs()), ErpSellerStoreProduct::getImageURLs, bo.getImageURLs());
        lqw.like(StringUtils.isNotBlank(bo.getSubject()), ErpSellerStoreProduct::getSubject, bo.getSubject());
        lqw.eq(StringUtils.isNotBlank(bo.getWhite()), ErpSellerStoreProduct::getWhite, bo.getWhite());
        lqw.eq(StringUtils.isNotBlank(bo.getMarketing()), ErpSellerStoreProduct::getMarketing, bo.getMarketing());
        lqw.eq(StringUtils.isNotBlank(bo.getMedia()), ErpSellerStoreProduct::getMedia, bo.getMedia());
        lqw.eq(StringUtils.isNotBlank(bo.getProductPrice()), ErpSellerStoreProduct::getProductPrice,
                bo.getProductPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getMobileDetail()), ErpSellerStoreProduct::getMobileDetail,
                bo.getMobileDetail());
        lqw.eq(bo.getPackageLength() != null, ErpSellerStoreProduct::getPackageLength, bo.getPackageLength());
        lqw.eq(StringUtils.isNotBlank(bo.getPackageWidth()), ErpSellerStoreProduct::getPackageWidth,
                bo.getPackageWidth());
        lqw.eq(bo.getPackageHeight() != null, ErpSellerStoreProduct::getPackageHeight, bo.getPackageHeight());
        lqw.eq(StringUtils.isNotBlank(bo.getGrossWeight()), ErpSellerStoreProduct::getGrossWeight, bo.getGrossWeight());
        lqw.eq(bo.getProductUnit() != null, ErpSellerStoreProduct::getProductUnit, bo.getProductUnit());
        lqw.eq(StringUtils.isNotBlank(bo.getCustomAttributes()), ErpSellerStoreProduct::getCustomAttributes,
                bo.getCustomAttributes());
        lqw.eq(StringUtils.isNotBlank(bo.getDetail()), ErpSellerStoreProduct::getDetail, bo.getDetail());
        lqw.eq(StringUtils.isNotBlank(bo.getDetailImg()), ErpSellerStoreProduct::getDetailImg, bo.getDetailImg());
        lqw.eq(bo.getSizechartId() != null, ErpSellerStoreProduct::getSizechartId, bo.getSizechartId());
        lqw.eq(StringUtils.isNotBlank(bo.getCollectUrl()), ErpSellerStoreProduct::getCollectUrl, bo.getCollectUrl());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerStoreProduct::getRevision, bo.getRevision());
        lqw.orderByDesc(ErpSellerStoreProduct::getUpdateTime);
        return lqw;
    }

    /**
     * 新增卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean insertByBo(ErpSellerStoreProductBo bo) {
        ErpSellerStoreProduct add = BeanUtil.toBean(bo, ErpSellerStoreProduct.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean updateByBo(ErpSellerStoreProductBo bo) {
        ErpSellerStoreProduct update = BeanUtil.toBean(bo, ErpSellerStoreProduct.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerStoreProduct entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R<Object> publish(String sellerProductIds, Long storeId, Long stock,
                             ErpSellerStoreProductExpand erpSellerStoreProductExpand) {

        List<String> asList = Arrays.asList(sellerProductIds.split(","));
        for (String string : asList) {
            Long sellerProductId = Long.valueOf(string);
            ErpSellerStoreProductExpand expand = new ErpSellerStoreProductExpand();
            BeanUtils.copyProperties(erpSellerStoreProductExpand, expand);

            push(sellerProductId, storeId, stock, expand);
        }
        return R.ok("发布成功");
    }

    /**
     * @param absoluteQuoteMapStr   区域定价
     * @param priceAdjustmentMethod 调价方式：0固定上调，1百分比上调
     * @param readjustPricesType    手动定价类型（0减去 1加上）
     * @param readjustPrices        调价
     * @param templateId            智能定价模板id
     * @param productPrice          商品价格
     * @return
     */
    @Override
    public Map<String, Object> countPrice(String absoluteQuoteMapStr, String priceAdjustmentMethod,
                                          Integer readjustPricesType, BigDecimal readjustPrices, String templateId, String productPrice) {
        Map<String, Object> map = new HashMap<>();
        map.put("absoluteQuoteMapStr", absoluteQuoteMapStr);
        map.put("productPrice", productPrice);

        Double min = null;
        Double max = null;

        // 获取是否有个别国家关税调整策略
        Map<String, ErpProductPriceControl> controlMap = iErpProductPriceControlService.getListByType("1"); // 关税

        // 判断调价方式
        if (priceAdjustmentMethod.equals("0")) { // 手动
            // 判断是否为0
            if (readjustPrices.compareTo(BigDecimal.ZERO) == 0)
                return map;
            // 判断上调还是下调
            if (readjustPricesType.equals(0)) // 下调
                readjustPrices = readjustPrices.negate();
            readjustPrices = BigDecimal.ONE
                    .add(readjustPrices.divide(new BigDecimal(100)).setScale(4, BigDecimal.ROUND_HALF_UP));

            map.put("readjustPrices", readjustPrices);

            List<Dict> absoluteQuoteMapList = JsonUtils.parseArrayMap(absoluteQuoteMapStr);
            // 获取运费，修改金额
            for (Dict dict : absoluteQuoteMapList) {
                String shiptoCountry = (String) dict.get("shiptoCountry");
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                for (String key : absoluteQuoteMap.keySet()) {
                    BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());
                    amount = amount.multiply(readjustPrices).setScale(2, BigDecimal.ROUND_HALF_UP);

                    Double res = amount.doubleValue();
                    absoluteQuoteMap.put(key, res);
                    if (min == null || res < min)
                        min = res;
                    if (max == null || res > max)
                        max = res;
                }
                // 计算个别国家调价
                absoluteQuoteMap = controlPrice(controlMap, absoluteQuoteMap, shiptoCountry);
            }
            // 获取完成的区域定价
            absoluteQuoteMapStr = JsonUtils.toJsonString(absoluteQuoteMapList);

        } else if (priceAdjustmentMethod.equals("1")) { // 自动

            List<Dict> absoluteQuoteMapList = JsonUtils.parseArrayMap(absoluteQuoteMapStr);

            // 获取模板
            R<Object> priceTemplateObject = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateById(Long.valueOf(templateId));
            if (priceTemplateObject.getCode() != 200) {
                Log.error("未获取到该模版");
                return null;
            }

            String priceTemplateString = JSONObject.toJSONString(priceTemplateObject.getData());
            ErpSellerStorePriceTemplate priceTemplate = JSONObject.parseObject(priceTemplateString, ErpSellerStorePriceTemplate.class);

            //ErpSellerStorePriceTemplate priceTemplate = (ErpSellerStorePriceTemplate) objectR.getData();

            BigDecimal discount = priceTemplate.getDiscount(); // 折扣比例
            BigDecimal union = priceTemplate.getUnion(); // 联盟比例
            BigDecimal transaction = priceTemplate.getTransaction(); // 交易费比例
            BigDecimal profit = priceTemplate.getProfit(); // 预估利润比例
            Integer type = priceTemplate.getType(); // 类型 1标准比例 2最低利润 3固定利润

            BigDecimal oneHundred = new BigDecimal(100);
            BigDecimal proportion = new BigDecimal(100); // 比例
            BigDecimal profitNum = new BigDecimal(100); // 利润值

            if (type.equals(1)) { // 1 标准比例

                profitNum = BigDecimal.ZERO;

                proportion = (BigDecimal.ONE.add(profit.divide(oneHundred)))
                        .divide(BigDecimal.ONE.subtract(union.add(transaction).divide(oneHundred)), 4,
                                BigDecimal.ROUND_HALF_EVEN)
                        .divide(BigDecimal.ONE.subtract(discount.divide(oneHundred)), 4, BigDecimal.ROUND_HALF_EVEN);
            } else if (type.equals(2)) { // 2 最低利润

                // 根据区域定价来确定最低的金额，然后最低的金额获取最低的利润值，就是最低利润

                BigDecimal minAmount = null;

                for (Dict dict : absoluteQuoteMapList) {
                    Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                    for (String key : absoluteQuoteMap.keySet()) {
                        BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());

                        if (minAmount == null) {
                            minAmount = amount;
                        } else {
                            if (minAmount.compareTo(amount) == 1) // 最小值大于本值，就重新赋值
                                minAmount = amount;
                        }
                    }
                }

                // 获取到最小的值，计算利润
                profitNum = minAmount.multiply(profit.divide(oneHundred)).setScale(4, BigDecimal.ROUND_HALF_EVEN);

                // 比例只算联盟、交易、折扣
                proportion = BigDecimal.ONE
                        .divide(BigDecimal.ONE.subtract(union.add(transaction).divide(oneHundred)), 4,
                                BigDecimal.ROUND_HALF_EVEN)
                        .divide(BigDecimal.ONE.subtract(discount.divide(oneHundred)), 4, BigDecimal.ROUND_HALF_EVEN);
            } else if (type.equals(3)) { // 3 固定利润，利润就是传过来的值

                profitNum = profit;

                // 比例只算联盟、交易、折扣
                proportion = BigDecimal.ONE
                        .divide(BigDecimal.ONE.subtract(union.add(transaction).divide(oneHundred)), 4,
                                BigDecimal.ROUND_HALF_EVEN)
                        .divide(BigDecimal.ONE.subtract(discount.divide(oneHundred)), 4, BigDecimal.ROUND_HALF_EVEN);
            }

            map.put("readjustPrices", proportion);
            map.put("profitNum", profitNum);

            // 获取运费，修改金额
            for (Dict dict : absoluteQuoteMapList) {
                String shiptoCountry = (String) dict.get("shiptoCountry");
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                for (String key : absoluteQuoteMap.keySet()) {
                    BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());
                    amount = (amount.add(profitNum)).multiply(proportion).setScale(2, BigDecimal.ROUND_HALF_UP);

                    Double res = amount.doubleValue();
                    absoluteQuoteMap.put(key, res);
                    if (min == null || res < min)
                        min = res;
                    if (max == null || res > max)
                        max = res;
                }
                // 计算个别国家调价
                absoluteQuoteMap = controlPrice(controlMap, absoluteQuoteMap, shiptoCountry);
            }
            // 获取完成的区域定价
            absoluteQuoteMapStr = JsonUtils.toJsonString(absoluteQuoteMapList);
        }

        productPrice = min.equals(max) ? min + "" : min + "-" + max;
        map.put("productPrice", productPrice);
        map.put("absoluteQuoteMapStr", absoluteQuoteMapStr);
        return map;
    }

    @Transactional
    @Override
    public R<Object> fission(Long sellerStoreProductId) {

        // 获取在线商品的信息
        ErpSellerStoreProduct sellerProduct = baseMapper.selectById(sellerStoreProductId);

        // 获取扩展信息
        ErpSellerStoreProductExpand expand = erpSellerStoreProductExpandMapper
                .selectOne(new LambdaQueryWrapper<ErpSellerStoreProductExpand>()
                        .eq(ErpSellerStoreProductExpand::getSellerStoreProductId, sellerStoreProductId));

        // 获取sku列表
        List<ErpSellerStoreProductSku> skuList = erpSellerStoreProductSkuMapper
                .selectList(new LambdaQueryWrapper<ErpSellerStoreProductSku>()
                        .eq(ErpSellerStoreProductSku::getSellerStoreProductId, sellerStoreProductId));

        // 保存
        sellerProduct.setId(null);
        sellerProduct.setAeProductId(null);
        sellerProduct.setCreateTime(null);
        sellerProduct.setUpdateTime(null);
        baseMapper.insert(sellerProduct);

        expand.setId(null);
        expand.setSellerStoreProductId(sellerProduct.getId());
        expand.setProductStatusType("-1");
        expand.setStatus(0); // 未发布
//		expand.setProductStatusType(null);
        expand.setAeProductId(null);
        expand.setCreateTime(null);
        expand.setUpdateTime(null);
        erpSellerStoreProductExpandMapper.insert(expand);

        for (ErpSellerStoreProductSku erpSellerStoreProductSku : skuList) {
            erpSellerStoreProductSku.setId(null);
            erpSellerStoreProductSku.setSellerStoreProductId(sellerProduct.getId());
            erpSellerStoreProductSku.setAeProductId(null);
            erpSellerStoreProductSku.setCreateTime(null);
            erpSellerStoreProductSku.setUpdateTime(null);
            erpSellerStoreProductSkuMapper.insert(erpSellerStoreProductSku);
        }

        return R.ok("商品裂变成功");
    }

    @Override
    public List<Map<String, Object>> getSkuNameById(Long id) {
        List<ErpSellerStoreProductSku> skuList = erpSellerStoreProductSkuMapper
                .selectList(new LambdaQueryWrapper<ErpSellerStoreProductSku>()
                        .eq(ErpSellerStoreProductSku::getSellerStoreProductId, id));
        ErpSellerStoreProduct sellerStoreProduct = baseMapper.selectById(id);
        List<Map<String, Object>> listMap = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for (ErpSellerStoreProductSku sku : skuList) {
            String skuPropertyIds = sku.getSkuPropertyIds();
            String skuProperty = "";
            if (StringUtils.isNotEmpty(skuPropertyIds)) {
                String[] split = skuPropertyIds.split(";");
                for (int i = 0; i < split.length; i++) {
                    String[] propertyList = split[i].split(":");
                    for (int j = 0; j < propertyList.length; j++) {
                        if ((j + 1) % 2 == 1) {
                            ErpCollectProductExpand collectProductExpand = collectProductExpandMapper
                                    .selectOne(new LambdaQueryWrapper<ErpCollectProductExpand>().eq(
                                            ErpCollectProductExpand::getCollectProductId,
                                            sellerStoreProduct.getCollectProductId()));
                            String skuPropertyJson = collectProductExpand.getSkuProperty();
                            JSONArray keyAndValueArray = JSON.parseArray(skuPropertyJson);
                            for (int i1 = 0; i1 < keyAndValueArray.size(); i1++) {
                                JSONObject jsonObject = keyAndValueArray.getJSONObject(i1);
                                String keyValue = jsonObject.getString("value");
                                if (propertyList[j].equals(keyValue)) {
                                    String name = jsonObject.getString("name");
                                    skuProperty = "".equals(skuProperty) ? name + "：" : skuProperty + name + "：";
                                    JSONArray list = jsonObject.getJSONArray("list");
                                    for (int i2 = 0; i2 < list.size(); i2++) {
                                        JSONObject valueObject = list.getJSONObject(i2);
                                        String value = valueObject.getString("value");
                                        if (propertyList[j + 1].equals(value)) {
                                            String valueName = valueObject.getString("name");
                                            skuProperty = skuProperty + valueName + "；";
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    String substring = skuProperty.substring(0, skuProperty.length() - 1);
                    map.put("value", sku.getId());
                    map.put("label", substring);
                    listMap.add(map);
                    map = new HashMap<>();
                }
            }
        }
        return listMap;
    }

    @Override
    public R<Object> restartpublish(Long sellerStoreProductId) {
        LambdaUpdateWrapper<ErpSellerStoreProductExpand> luw = Wrappers.lambdaUpdate();
        luw.set(ErpSellerStoreProductExpand::getProductStatusType, "-1");
        luw.set(ErpSellerStoreProductExpand::getStatus, 0);
        luw.set(ErpSellerStoreProductExpand::getRemark, null);
        luw.eq(ErpSellerStoreProductExpand::getSellerStoreProductId, sellerStoreProductId);
        erpSellerStoreProductExpandMapper.update(null, luw);
        return R.ok();
    }


    private Map<String, Object> controlPrice(Map<String, ErpProductPriceControl> controlMap,
                                             Map<String, Object> absoluteQuoteMap, String shiptoCountry) {

        // 判断该国家是否需要调价
        if (controlMap.containsKey(shiptoCountry)) {

            ErpProductPriceControl control = controlMap.get(shiptoCountry);

            for (String key : absoluteQuoteMap.keySet()) {
                BigDecimal price = new BigDecimal((Double) absoluteQuoteMap.get(key));

                String controlWay = control.getControlWay(); // 调价方式（1固定 2百分比）
                String priceType = control.getPriceType(); // 加减类型 （1加上 2减去）
                BigDecimal amount = new BigDecimal(control.getAmount()); // 价格

                if (controlWay.equals("1")) { // 固定
//					if (priceType.equals("1")) { // 加上
                    price = price.add(amount);
//					} else if (priceType.equals("2")) { // 减去
//						price = price.subtract(amount);
//					}
                } else if (controlWay.equals("2")) { // 百分比
                    BigDecimal subtract = BigDecimal.ONE.subtract(amount.divide(BigDecimal.valueOf(100)));
                    price = price.divide(subtract, 2,
                            BigDecimal.ROUND_HALF_UP);
//					if (priceType.equals("1")) { // 加上
//						price = price.add(amount);
//					} else if (priceType.equals("2")) { // 减去
//						price = price.subtract(amount);
//					}
                }
                Double res = price.doubleValue();
                absoluteQuoteMap.put(key, res);
            }
        }

        return absoluteQuoteMap;
    }

    /**
     * 查询卖家在线商品;参考AE-商品：发布产品信息（aliexpress.postproduct.redefining.postaeproduct）列表
     */
    @Override
    public TableDataInfo<ErpSellerStoreProductVo> queryPageList(ErpSellerStoreProductBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpSellerStoreProduct> lqw = buildQueryWrapper(bo);

        List<SFunction<ErpSellerStoreProduct, ?>> columns = new ArrayList<>();
        columns.add(ErpSellerStoreProduct::getId);
        columns.add(ErpSellerStoreProduct::getSubject);
        columns.add(ErpSellerStoreProduct::getCollectProductId);
        columns.add(ErpSellerStoreProduct::getWhite);
        columns.add(ErpSellerStoreProduct::getProductPrice);
        columns.add(ErpSellerStoreProduct::getAeProductId);
        columns.add(ErpSellerStoreProduct::getCreateTime);
        columns.add(ErpSellerStoreProduct::getUpdateBy);
        columns.add(ErpSellerStoreProduct::getUpdateTime);
        columns.add(ErpSellerStoreProduct::getStoreId);
        columns.add(ErpSellerStoreProduct::getImageURLs);
        lqw.select(columns);

        // 查看是否是超级管理员
        if (!SecurityUtils.isAdminNew()) {
            // 修改查看权限

            ErpSellerStoreEmpower storeEmpower = new ErpSellerStoreEmpower();
            storeEmpower.setId(bo.getStoreId());
            storeEmpower.setUserId(SecurityUtils.getUserId());
            R<Object> sellerStoreListR = remoteSellerStoreService.getSellerStoreListByInfo(storeEmpower);
            String sellerStoreListString = JSONObject.toJSONString(sellerStoreListR.getData());
            List<ErpSellerStoreEmpower> selectList = JSONArray.parseArray(sellerStoreListString, ErpSellerStoreEmpower.class);

            List<String> collect = selectList.stream().map(store -> store.getStoreUserName())
                    .collect(Collectors.toList());
            if (collect != null && collect.size() > 0) {
                // 根据名称获取id集合
                R<Object> storeListR = remoteSellerStoreService.selectEmpowerInUserName(collect);
                String storeListString = JSONObject.toJSONString(storeListR.getData());
                List<ErpSellerStoreEmpower> list = JSONArray.parseArray(storeListString, ErpSellerStoreEmpower.class);

                List<Long> collect1 = list.stream().map(store -> store.getId()).collect(Collectors.toList());

                lqw.in(ErpSellerStoreProduct::getStoreId, collect1);
            } else {
                lqw.isNull(ErpSellerStoreProduct::getId);
            }
        } else {
            lqw.eq(bo.getStoreId() != null, ErpSellerStoreProduct::getStoreId, bo.getStoreId());
        }

        Page<ErpSellerStoreProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (ErpSellerStoreProductVo vo : result.getRecords()) {
            // 获取erp商品状态collectProductStatus
            LambdaQueryWrapper<ErpCollectProductExpand> collectexpandlqw = new LambdaQueryWrapper<ErpCollectProductExpand>();
            collectexpandlqw.select(ErpCollectProductExpand::getId, ErpCollectProductExpand::getProductStatus);
            collectexpandlqw.eq(ErpCollectProductExpand::getCollectProductId, vo.getCollectProductId());
            ErpCollectProductExpand collectProductExpand = collectProductExpandMapper.selectOne(collectexpandlqw);
            Integer productStatus = 0;
            if (collectProductExpand != null) {
                productStatus = collectProductExpand.getProductStatus();
            }
            vo.setCollectProductStatus(productStatus);

            // 修改人
//            R<Object> userR = remoteUserService.selectUserById(Long.valueOf(vo.getUpdateBy()));
//            String userString = JSONObject.toJSONString(userR.getData());
//            SysUser user = JSONObject.parseObject(userString, SysUser.class);
//            vo.setUpdateBy(user.getNickName());

//			// 获取sku
//			List<ErpSellerStoreProductSkuVo> skuList = erpSellerStoreProductSkuMapper
//					.selectVoList(new LambdaQueryWrapper<ErpSellerStoreProductSku>()
//							.eq(ErpSellerStoreProductSku::getSellerStoreProductId, vo.getId()));
//			vo.setSkuList(skuList);

            // 获取扩展表
            LambdaQueryWrapper<ErpSellerStoreProductExpand> expandlqw = new LambdaQueryWrapper<ErpSellerStoreProductExpand>();
            List<SFunction<ErpSellerStoreProductExpand, ?>> expandcolumns = new ArrayList<>();
            expandcolumns.add(ErpSellerStoreProductExpand::getId);
            expandcolumns.add(ErpSellerStoreProductExpand::getPriceAdjustmentMethod);
            expandcolumns.add(ErpSellerStoreProductExpand::getReadjustPricesType);
            expandcolumns.add(ErpSellerStoreProductExpand::getReadjustPrices);
            expandcolumns.add(ErpSellerStoreProductExpand::getTemplateId);
            expandcolumns.add(ErpSellerStoreProductExpand::getProductStatusType);
            expandcolumns.add(ErpSellerStoreProductExpand::getStatus);
            expandcolumns.add(ErpSellerStoreProductExpand::getRemark);
            expandcolumns.add(ErpSellerStoreProductExpand::getActivityRemark);
            expandlqw.select(expandcolumns);
            expandlqw.eq(ErpSellerStoreProductExpand::getSellerStoreProductId, vo.getId());
            ErpSellerStoreProductExpandVo expandVo = erpSellerStoreProductExpandMapper.selectVoOne(expandlqw);
            if (Objects.isNull(expandVo)) {
                continue;
            }
            // 获取模板名称
            if (expandVo.getPriceAdjustmentMethod().equals("1")) {
                R<Object> templateR = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateById(Long.valueOf(expandVo.getTemplateId()));
                String templateString = JSONObject.toJSONString(templateR.getData());
                ErpSellerStorePriceTemplate template = JSONObject.parseObject(templateString, ErpSellerStorePriceTemplate.class);
                if (template != null)
                    expandVo.setTemplateName(template.getTemplateName());
            }
            vo.setExpand(expandVo);

            ErpSellerStoreProductGroup group = erpSellerStoreProductGroupMapper
                    .selectOne(new LambdaQueryWrapper<ErpSellerStoreProductGroup>()
                            .eq(ErpSellerStoreProductGroup::getAeProductId, vo.getAeProductId())
                            .eq(ErpSellerStoreProductGroup::getAeProductId, bo.getGroupId()));
            if (ObjectUtils.isNotEmpty(group)) {
                vo.setGroupTaskStatus(group.getStatus());
            }

        }
        return TableDataInfo.build(result);
    }

    //    @Override
//    @Async
//    public void push(ErpSellerStoreProductExpand expand) {
//        StringBuffer msg = new StringBuffer();
//        // 发布商品
//        try {
//            ErpSellerStoreProduct sellerProduct = baseMapper.selectById(expand.getSellerStoreProductId());
//            Integer postType = 1;
//            R<String> res = iAeProductService.disposeProductData(sellerProduct.getId(), sellerProduct.getStoreId(), 1);
//            if (res.getCode() == 200) { // 发布成功
//                expand.setStatus(2);
//                expand.setProductStatusType("0");
//                msg.append("发布成功");
//            } else { // 发布失败
//                expand.setProductStatusType("-2");
//                expand.setStatus(3);
//                msg.append(res.getMsg() + "|");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            expand.setStatus(3); // 发布失败
////            erpSellerStoreProductExpandMapper.updateById(expand);
//            msg.append(e.getMessage() + "|");
//        }
//
//        expand.setRemark(expand.getRemark());
//        erpSellerStoreProductExpandMapper.updateById(expand);
//        ErpSellerStoreProductExpand expandSel = erpSellerStoreProductExpandMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerStoreProductExpand>()
//                        .eq(ErpSellerStoreProductExpand::getSellerStoreProductId, expand.getSellerStoreProductId())
//        );
//        if (expandSel.getStatus() == 2) {
//            confirmUploadSuccess(expandSel.getSellerStoreProductId());
//        }
//    }
//
//
//
//    @Override
//    @Async
//    public void confirmUploadSuccess(Long erpSellerStoreProductId) {
//        ErpSellerStoreProduct sellerProduct = baseMapper.selectById(erpSellerStoreProductId);
//        ErpSellerStoreProductExpand expand = erpSellerStoreProductExpandMapper.selectOne(
//                new LambdaQueryWrapper<ErpSellerStoreProductExpand>().eq(ErpSellerStoreProductExpand::getSellerStoreProductId, erpSellerStoreProductId)
//        );
//        StringBuffer msg = new StringBuffer();
//        sleep(5000);
//        Boolean flag = true;
//        R<Object> AuditType = findAeProductStatusById(sellerProduct.getId());
//        if (ObjectUtils.isNotNull(expand.getIsAudit()) && AuditType.getCode() != 200) {
//            expand.setProductStatusType("-3");
//            expand.setStatus(3);
//            // 下架商品
//            productOfflineOrOnline(sellerProduct.getId().toString(), sellerProduct.getStoreId(), 0);
//            ErpSellerStoreProduct product = baseMapper.selectById(sellerProduct.getId());
//            // 8、删除产品
//            if (ObjectUtils.isNotNull(expand.getAutoTaskId())) {
//                deleteProductToAe(product.getAeProductId(), sellerProduct.getStoreId());
//                msg.append("产品进入审核中状态，系统将其自动下架并删除|");
//                flag = false;
//            } else {
//                msg.append("产品进入审核中状态，系统将其自动下架|");
//            }
//        }
//
//        if (flag) {
//            Long aeProductId = sellerProduct.getAeProductId();
//            List<ErpSellerStoreProductSku> erpSellerStoreProductSkuList = erpSellerStoreProductSkuMapper
//                    .selectList(new LambdaQueryWrapper<ErpSellerStoreProductSku>()
//                            .eq(ErpSellerStoreProductSku::getSellerStoreProductId, erpSellerStoreProductId));
//            for (ErpSellerStoreProductSku sku : erpSellerStoreProductSkuList) {
//                sku.setAeProductId(aeProductId);
//            }
//            erpSellerStoreProductSkuMapper.updateBatchById(erpSellerStoreProductSkuList);
//
//
//            // 发布商品至营销活动
//            if (expand.getActivityId() != null) {
//                ErpSellerStorePriceTemplate priceTemplate = erpSellerStorePriceTemplateMapper
//                        .selectById(expand.getTemplateId());
//                if (priceTemplate != null) {
//                    R<Object> objectR = iAePromotionActivityService.addProductToActivity(sellerProduct.getId(), expand.getActivityId(),
//                            priceTemplate.getDiscount());
//                    if (objectR.getCode() != 200) {
//                        expand.setStatus(3);
//                        msg.append("活动设置异常|");
//                    }
//                }
//            }
//
//            if (expand.getGroupId() != null) {
//                ErpSellerStoreGroup group = erpSellerStoreGroupMapper
//                        .selectOne(new LambdaQueryWrapper<ErpSellerStoreGroup>().eq(ErpSellerStoreGroup::getGroupId,
//                                expand.getGroupId()));
//                if (group != null) {
//                    R<Object> objectR = erpSellerStoreProductGroupService
//                            .bindingProdudtForGroup(sellerProduct.getId().toString(), expand.getGroupId());
//                    if (objectR.getCode() == 200) {
//                        Map<String, Object> map = (Map<String, Object>) objectR.getData();
//                        erpSellerStoreProductGroupService.sendProductGroupToAe(map);
//                    } else {
//                        expand.setStatus(3);
//                        msg.append("分组设置异常|");
//                    }
//                }
//            }
//        }
//
//
//        expand.setRemark(expand.getRemark() + "|" + msg.toString());
//        erpSellerStoreProductExpandMapper.updateById(expand);
//
//        //查找延伸表
//        ErpCollectProductExpand erpCollectProductExpand = collectProductExpandMapper.selectOne(
//                new LambdaQueryWrapper<ErpCollectProductExpand>()
//                        .eq(ErpCollectProductExpand::getCollectProductId, sellerProduct.getCollectProductId())
//        );
//        if (ObjectUtils.isNotNull(erpCollectProductExpand)) {
//            erpCollectProductExpand.setIsViola(9);
//            collectProductExpandMapper.updateById(erpCollectProductExpand);
//        }
//        //若有问题
//        if (expand.getStatus() == 3) {
//            if (ObjectUtils.isNotNull(expand.getAutoTaskId())) {
//                //自动化的任务，则调用方法通知auto接口
//                restTemplate.getForEntity(autoConfig.getEndpoint() + "/pulishProduct/autoPulishProductProjectTask/confirmUploadSuccess?taskId=" + expand.getAutoTaskId() + "&msg=" + expand.getRemark(), String.class);
//            }
//        }
//
//    }
//
//    @Override
//    public R<Object> findAeProductStatusById(Long productId) {
//        ErpSellerStoreProduct product = baseMapper.selectById(productId);
//        if (product == null) {
//            return R.fail("商品不存在");
//        }
//        if (product.getAeProductId() == null) {
//            return R.fail("该商品尚未发布");
//        }
//        Map<String, Object> map = new HashMap<>();
//        map.put("storeId", product.getStoreId());
//        map.put("productId", product.getAeProductId());
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/findAeProductStatusById", map, String.class);
//        String body = (String) forEntity.getBody();
//        String msg = JSONObject.parseObject(body).getString("msg");
//        System.out.println(msg);
//        if (!msg.equals("approved")) {
//            // 审核未通过或审核中
//            return R.fail(msg);
//        } else {
//            return R.ok(msg);
//        }
//    }
//
//    @Override
//    public R<Object> queryProductBusinessInfoById(Long productId) {
//        ErpSellerStoreProduct product = baseMapper.selectById(productId);
//        if (product == null) {
//            return R.fail("商品不存在");
//        }
//        if (product.getAeProductId() == null) {
//            return R.fail("该商品尚未发布");
//        }
//        Map<String, Object> map = new HashMap<>();
//        map.put("storeId", product.getStoreId());
//        map.put("productId", product.getAeProductId());
//        ResponseEntity<String> forEntity = restTemplate.postForEntity(
//                aeConfig.getEndpoint() + "/erp/erpProduct/queryProductBusinessInfoById", map, String.class);
//        String body = (String) forEntity.getBody();
//        String msg = JSONObject.parseObject(body).getString("msg");
//        System.out.println(msg);
//        return null;
//    }
//
    public R<String> productOfflineOrOnline(String sellerStoreProductIds, Long sellerId, Integer type) {
        Map<String, Object> returnMap = new HashMap<>();
//        if (StringUtils.isEmpty(checkSellerId(sellerId))) {
//            return R.ok("店铺未授权");
//        }
//        //确认该商品是否存在
//        ErpSellerStoreProductVo erpSellerProduct = iErpSellerStoreProductService.queryById(sellerStoreProductId);
//        if (erpSellerProduct == null) {
//            return R.ok("商品不存在");
//        }
        ResponseEntity<String> forEntity = null;
        String body = null;
        returnMap.put("product_ids", sellerStoreProductIds);
        returnMap.put("sellerId", sellerId);
        List<String> productIdList = Arrays.asList(sellerStoreProductIds.split(";"));
        ErpSellerStoreProduct erpSellerStoreProduct = new ErpSellerStoreProduct();
        ErpSellerStoreProductExpand erpSellerStoreProductExpand = new ErpSellerStoreProductExpand();
        for (String productId : productIdList) {
            erpSellerStoreProductExpand = erpSellerStoreProductExpandMapper
                    .selectOne(new LambdaQueryWrapper<ErpSellerStoreProductExpand>()
                            .eq(ErpSellerStoreProductExpand::getSellerStoreProductId, productId));

            if (type == 0) {
                if (!erpSellerStoreProductExpand.getProductStatusType().equals("1")) {
                    returnMap.put("product_ids", erpSellerStoreProductExpand.getAeProductId());
                    // 下架商品
                    R<Object> objectR = remoteAeProductService.offlineAeProduct(returnMap);
//                    forEntity = restTemplate.postForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/offlineAeProduct",
//                            returnMap, String.class);
                    body = (String) objectR.getData();
                    System.out.println(body);
                    System.out.println(objectR.getMsg());
                    Integer code = objectR.getCode();
                    if (code == 200) {
//                        Integer modifyCount = JSONObject.parseObject(body)
//                                .getJSONObject("aliexpress_postproduct_redefining_offlineaeproduct_response")
//                                .getJSONObject("result").getInteger("modify_count");
                        erpSellerStoreProductExpand.setProductStatusType("0");
                        erpSellerStoreProductExpandMapper.updateById(erpSellerStoreProductExpand);
                    } else {
                        return R.fail("下架失败");
                    }
                } else {
                    return R.fail("该商品当前状态已为下架");
                }
            } else {
                if (erpSellerStoreProductExpand.getProductStatusType().equals("1")) {
                    returnMap.put("product_ids", productId);
                    // 上架商品
                    R<Object> objectR = remoteAeProductService.onlineAeProduct(returnMap);
//                    forEntity = restTemplate.postForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/onlineaeproduct",
//                            returnMap, String.class);
                    body = (String) objectR.getData();
                    Integer code = JSONObject.parseObject(body).getInteger("code");
                    if (code == 200) {
//                        Integer modifyCount = JSONObject.parseObject(body).getJSONObject("msg")
//                                .getJSONObject("aliexpress_postproduct_redefining_onlineaeproduct_response")
//                                .getJSONObject("result").getInteger("modify_count");
                        erpSellerStoreProductExpand.setProductStatusType("1");
                        erpSellerStoreProductExpandMapper.updateById(erpSellerStoreProductExpand);
                    } else {
                        return R.fail("上架失败");
                    }
                } else {
                    return R.fail("该商品当前状态不为下架");
                }
            }
        }
        return R.ok("执行成功");

    }

    //
    public R<Object> deleteProductToAe(Long productId, Long sellerId) {
//        Map<String, Object> z = new HashMap<>();
//        if (StringUtils.isEmpty(checkSellerId(sellerId))) {
//            return R.ok("店铺未授权");
//        }
//        确认该商品是否存在
//        ErpSellerStoreProductVo erpSellerProduct = iErpSellerStoreProductService.queryById(productId);
//        if (erpSellerProduct == null) {
//            return R.ok("商品不存在");
//        }
        //Ae接口
        R<Object> objectR = remoteAeProductService.deleteProductToAe(productId, sellerId);
//        ResponseEntity<String> forEntity = restTemplate
//                .getForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/deleteProduct?productId=" + productId + "&sellerId=" + sellerId, String.class);
        String body = (String) objectR.getData();
        Integer code = JSONObject.parseObject(body).getInteger("code");
        if (code == 200) {
            return R.ok("删除商品成功");
        } else {
            return R.fail("删除商品失败");
        }
    }


    @Override
    public R<Object> getSellerStoreProductInfo(ErpSellerStoreProduct erpSellerStoreProduct) {
        ErpSellerStoreProductBo erpSellerStoreProductBo = BeanUtil.copyProperties(erpSellerStoreProduct, ErpSellerStoreProductBo.class);
        LambdaQueryWrapper<ErpSellerStoreProduct> erpSellerStoreProductLambdaQueryWrapper = buildQueryWrapperNew(erpSellerStoreProductBo);
        ErpSellerStoreProduct erpSellerStoreProductSel = baseMapper.selectOne(erpSellerStoreProductLambdaQueryWrapper);
        if (Objects.isNull(erpSellerStoreProductSel)) {
            return R.fail("未查到信息");
        } else {
            return R.ok(erpSellerStoreProductSel);
        }
    }

    @Override
    public R<Object> deleteErpSellerStoreProduct(ErpSellerStoreProduct erpSellerStoreProduct) {
        int i = baseMapper.deleteById(erpSellerStoreProduct);
        if (i > 0) {
            return R.ok("删除成功");
        } else {
            return R.fail("删除失败");
        }
    }

    @Override
    public R<Object> push(Long sellerStoreProductId) {

        StringBuffer msg = new StringBuffer();

        // 获取未发布的商品
        ErpSellerStoreProductExpand expand = erpSellerStoreProductExpandMapper
                .selectOne(new LambdaQueryWrapper<ErpSellerStoreProductExpand>()
                        .eq(ErpSellerStoreProductExpand::getSellerStoreProductId, sellerStoreProductId)
                        .last(" limit 1 "));
        expand.setStatus(1); // 发布中
        erpSellerStoreProductExpandMapper.updateById(expand);
        // 发布商品
        try {
            ErpSellerStoreProduct sellerProduct = baseMapper.selectById(expand.getSellerStoreProductId());
            Integer postType = 1;
            R<Object> res = iAeProductService.disposeProductData(sellerProduct.getId(), sellerProduct.getStoreId(), 1);
            if (res.getCode() == 200) { // 发布成功
                expand.setStatus(2);
                expand.setProductStatusType("0");
                msg.append("发布成功");
            } else { // 发布失败
                expand.setProductStatusType("-2");
                expand.setStatus(3);
                msg.append(res.getMsg() + "|");
            }
        } catch (Exception e) {
            e.printStackTrace();
            expand.setStatus(3); // 发布失败
//            erpSellerStoreProductExpandMapper.updateById(expand);
            msg.append(e.getMessage() + "|");
        }

        expand.setRemark(expand.getRemark());
        erpSellerStoreProductExpandMapper.updateById(expand);
        if (expand.getStatus() == 2) {
            confirmUploadSuccess(expand.getSellerStoreProductId());
            return R.ok(msg);
        } else {
            return R.fail(msg);
        }

    }

    @Override
    @Async
    public void confirmUploadSuccess(Long erpSellerStoreProductId) {
        ErpSellerStoreProduct sellerProduct = baseMapper.selectById(erpSellerStoreProductId);
        ErpSellerStoreProductExpand expand = erpSellerStoreProductExpandMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreProductExpand>().eq(ErpSellerStoreProductExpand::getSellerStoreProductId, erpSellerStoreProductId)
        );
        StringBuffer msg = new StringBuffer();
        sleep(5000);
        Boolean flag = true;
        R<Object> AuditType = findAeProductStatusById(sellerProduct.getId());
        if (ObjectUtils.isNotNull(expand.getIsAudit()) && AuditType.getCode() != 200) {
            expand.setProductStatusType("-3");
            expand.setStatus(3);
            // 下架商品
            productOfflineOrOnline(sellerProduct.getId().toString(), sellerProduct.getStoreId(), 0);
            ErpSellerStoreProduct product = baseMapper.selectById(sellerProduct.getId());
            // 8、删除产品
            if (ObjectUtils.isNotNull(expand.getAutoTaskId())) {
                deleteProductToAe(product.getAeProductId(), sellerProduct.getStoreId());
                msg.append("产品进入审核中状态，系统将其自动下架并删除|");
                flag = false;
            } else {
                msg.append("产品进入审核中状态，系统将其自动下架|");
            }
        }

        if (flag) {
            Long aeProductId = sellerProduct.getAeProductId();
            List<ErpSellerStoreProductSku> erpSellerStoreProductSkuList = erpSellerStoreProductSkuMapper
                    .selectList(new LambdaQueryWrapper<ErpSellerStoreProductSku>()
                            .eq(ErpSellerStoreProductSku::getSellerStoreProductId, erpSellerStoreProductId));
            for (ErpSellerStoreProductSku sku : erpSellerStoreProductSkuList) {
                sku.setAeProductId(aeProductId);
            }
            erpSellerStoreProductSkuMapper.updateBatchById(erpSellerStoreProductSkuList);


            // 发布商品至营销活动
            if (expand.getActivityId() != null) {
                R<Object> templateObject = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateById(Long.valueOf(expand.getTemplateId()));
                String templateString = JSONObject.toJSONString(templateObject.getData());
                ErpSellerStorePriceTemplate priceTemplate = JSONObject.parseObject(templateString, ErpSellerStorePriceTemplate.class);

                if (priceTemplate != null) {
                    //TODO 暂时屏蔽
//                    R<Object> objectR = iAePromotionActivityService.addProductToActivity(sellerProduct.getId(), expand.getActivityId(),
//                            priceTemplate.getDiscount());
//                    if (objectR.getCode() != 200) {
//                        expand.setStatus(3);
//                        msg.append("活动设置异常|");
//                    }
                }
            }

            if (expand.getGroupId() != null) {
                //TODO 暂时屏蔽
//                ErpSellerStoreGroup group = erpSellerStoreGroupMapper
//                        .selectOne(new LambdaQueryWrapper<ErpSellerStoreGroup>().eq(ErpSellerStoreGroup::getGroupId,
//                                expand.getGroupId()));
//                if (group != null) {
//                    R<Object> objectR = erpSellerStoreProductGroupService
//                            .bindingProdudtForGroup(sellerProduct.getId().toString(), expand.getGroupId());
//                    if (objectR.getCode() == 200) {
//                        Map<String, Object> map = (Map<String, Object>) objectR.getData();
//                        erpSellerStoreProductGroupService.sendProductGroupToAe(map);
//                    } else {
//                        expand.setStatus(3);
//                        msg.append("分组设置异常|");
//                    }
//                }
            }
        }


        expand.setRemark(expand.getRemark() + "|" + msg.toString());
        erpSellerStoreProductExpandMapper.updateById(expand);

        //查找延伸表
        ErpCollectProductExpand erpCollectProductExpand = collectProductExpandMapper.selectOne(
                new LambdaQueryWrapper<ErpCollectProductExpand>()
                        .eq(ErpCollectProductExpand::getCollectProductId, sellerProduct.getCollectProductId())
        );
        if (ObjectUtils.isNotNull(erpCollectProductExpand)) {
            erpCollectProductExpand.setIsViola(9);
            collectProductExpandMapper.updateById(erpCollectProductExpand);
        }
        //若有问题
        if (expand.getStatus() == 3) {
            if (ObjectUtils.isNotNull(expand.getAutoTaskId())) {
                //自动化的任务，则调用方法通知auto接口
                //TODO 暂时屏蔽
//                restTemplate.getForEntity(autoConfig.getEndpoint() + "/pulishProduct/autoPulishProductProjectTask/confirmUploadSuccess?taskId=" + expand.getAutoTaskId() + "&msg=" + expand.getRemark(), String.class);
            }
        }

    }

    @Override
    public R<Object> findAeProductStatusById(Long productId) {
        ErpSellerStoreProduct product = baseMapper.selectById(productId);
        if (product == null) {
            return R.fail("商品不存在");
        }
        if (product.getAeProductId() == null) {
            return R.fail("该商品尚未发布");
        }
        R<Object> objectR = remoteAeProductService.findAeProductStatusById(product.getAeProductId(), product.getStoreId());
        ;
        String msg = JSONObject.toJSONString(objectR.getData());
        System.out.println(msg);
        if (!msg.contains("approved")) {
            // 审核未通过或审核中
            return R.fail(msg);
        } else {
            return R.ok(msg);
        }
    }

    @Override
    public R<Object> getSellerStoreProductInfoById(String id) {
        ErpSellerStoreProduct erpSellerStoreProduct = baseMapper.selectById(id);
        if (Objects.isNull(erpSellerStoreProduct)) {
            return R.ok(null);
        } else {
            return R.ok(erpSellerStoreProduct);
        }
    }

    @Override
    public R<Object> selectRepeatProduct(String storeUserName, Long collectProductId) {
        ErpSellerStoreProduct product = baseMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreProduct>()
                        .eq(ErpSellerStoreProduct::getStoreUserName, storeUserName)
                        .eq(ErpSellerStoreProduct::getCollectProductId, collectProductId)
                        .isNotNull(ErpSellerStoreProduct::getAeProductId)
                        .eq(ErpSellerStoreProduct::getDelFlag, 0)
                        .last("limit 1")
        );
        if (Objects.isNull(product)) {
            return R.ok("不存在");
        } else {
            return R.fail("存在");
        }
    }


    /**
     * 根据店铺ID，获取店铺未下架商品数量
     *
     * @param storeId
     * @return
     */
    @Override
    public Long selectProductCountByStoreId(Long storeId) {
        Long count = baseMapper.selectProductCountByStoreId(storeId);
        if (count == null) {
            count = 0L;
        }
        return count;
    }

    @Override
    public List<ErpSellerStoreProduct> queryProductByCycle(Integer cycle, List<Long> storeId) {
        return baseMapper.queryProductByCycle(cycle, storeId);
    }

    @Override
    public ErpSellerStoreProduct getFarthestProduct(String storeUserName) {
        LambdaQueryWrapper<ErpSellerStoreProduct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ErpSellerStoreProduct::getStoreUserName, storeUserName);
        queryWrapper.orderByAsc(BaseEntity::getCreateTime);
        queryWrapper.isNotNull(ErpSellerStoreProduct::getAeProductId);
        queryWrapper.last("limit 1");
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 批量删除产品
     *
     * @return
     */
    @Override
    public R<Object> delectBatchProducts(Long storeId, Integer type, String storeUserName) {
        List<ErpSellerStoreProductExpand> list = new ArrayList<>();
        switch (type) {
            case 1:
                list = erpSellerStoreProductExpandMapper.selectNoVisitProductList(storeId, storeUserName);
                //删除无访客产品
                break;
            case 2:
                //整店产品删除
                list = erpSellerStoreProductExpandMapper.selectProductByStoreUserName(storeUserName);
                break;
        }

        if (list.size() == 0) {
            return R.fail("没有需要删除品");
        }
        for (ErpSellerStoreProductExpand expand : list) {
            R<Object> objectR = remoteAeProductService.deleteProductToAe(expand.getAeProductId(), storeId);
            if (objectR.getCode() == 200) {
                expand.setProductStatusType("6");
                erpSellerStoreProductExpandMapper.updateById(expand);
            }
        }


        return R.ok();
    }

    /**
     * 确认Ae商品信息状态
     *
     * @param
     * @return
     */
    @Override
    public R<Object> confirmAeProductInfoStatus(String storeUserName) {
        //循环获取商品信息
        List<ErpSellerStoreProductExpand> expandList = erpSellerStoreProductExpandMapper.selectConfirmProductByStoreUserName(storeUserName);
        for (ErpSellerStoreProductExpand product : expandList) {
            R<Object> objectR = remoteAeProductService.queryAeProduct(product.getAeProductId(), storeUserName);
            if (objectR.getCode() == 200) {
                String s = (String) objectR.getData();
                JSONObject productObject = JSONObject.parseObject(s)
                        .getJSONObject("aliexpress_offer_product_query_response")
                        .getJSONObject("result");
                String productStatusType = productObject.getString("product_status_type");
                System.out.println(productStatusType);
                switch (productStatusType) {
                    case "onSelling":
                        product.setProductStatusType("0");
                        break;
                    case "offline":
                        product.setProductStatusType("1");
                        break;
                }
            } else {
                product.setProductStatusType("1");
            }
            product.setConfrimAeStatus(1);
            erpSellerStoreProductExpandMapper.updateById(product);
        }
        return null;
    }


    @Override
    public void push(Long sellerProductId, Long storeId, Long stock,
                     ErpSellerStoreProductExpand erpSellerStoreProductExpand) {
        try {
            // 获取个人产品库的商品
            ErpSellerProduct erpSellerProduct = erpSellerProductMapper.selectById(sellerProductId);
            if (erpSellerProduct == null) {
                return;
            }

            // 获取个人产品库的商品sku
            List<ErpSellerProductSkuVo> productVoSkus = erpSellerProductSkuMapper
                    .selectVoList(new LambdaQueryWrapper<ErpSellerProductSku>()
                            .eq(ErpSellerProductSku::getSellerProductId, sellerProductId));

            // 获取个人产品库的商品扩展表
            ErpSellerProductExpandVo productExpandVo = erpSellerProductExpandMapper
                    .selectVoOne(new LambdaQueryWrapper<ErpSellerProductExpand>()
                            .eq(ErpSellerProductExpand::getSellerProductId, sellerProductId));

            // 修改商品价格
            Map<String, Object> absoluteQuoteMap = countPrice(productExpandVo.getAbsoluteQuoteMap(),
                    erpSellerStoreProductExpand.getPriceAdjustmentMethod(),
                    erpSellerStoreProductExpand.getReadjustPricesType(),
                    erpSellerStoreProductExpand.getReadjustPrices(), erpSellerStoreProductExpand.getTemplateId(),
                    erpSellerProduct.getProductPrice());
            if (Objects.isNull(absoluteQuoteMap)) {
                return;
            }

            // 保存到店铺在线商品
            ErpSellerStoreProduct sellerStoreProduct = new ErpSellerStoreProduct();
            BeanUtils.copyProperties(erpSellerProduct, sellerStoreProduct);
            sellerStoreProduct.setId(null);
            sellerStoreProduct.setSellerProductId(sellerProductId);
            sellerStoreProduct.setStoreId(storeId);
            sellerStoreProduct.setCreateTime(null);
            sellerStoreProduct.setUpdateTime(null);
            sellerStoreProduct.setCreateBy(erpSellerProduct.getSellerId() + "");
            sellerStoreProduct.setUpdateBy(erpSellerProduct.getSellerId() + "");

            sellerStoreProduct.setProductPrice((String) absoluteQuoteMap.get("productPrice"));

            String s = "";
            String brandId = erpSellerStoreProductExpand.getBrandId();
            if (StringUtils.isNotEmpty(brandId)) {

                Boolean bool = true;

                // 判断是否有这个品牌
                List<Aliexpress.ValueVo> valueList = aliexpressCategoryServiceImpl.getBrandById(sellerStoreProduct.getCategoryId(),
                        storeId);
                if (valueList == null || valueList.size() == 0) {
                    erpSellerStoreProductExpand.setProductStatusType("-2");
                    erpSellerStoreProductExpand.setStatus(3);
                    erpSellerStoreProductExpand.setRemark("没有匹配的品牌");
                } else {
                    for (Aliexpress.ValueVo valueVo : valueList) {
                        if (valueVo.getAttr_value_id().toString().equals(brandId))
                            bool = false;
                    }

                    if (bool) {
                        Aliexpress.ValueVo valueVo = valueList.get(0);
                        brandId = valueVo.getAttr_value_id().toString();
                    }
                }

                s = "[{\"attr_name\":\"\",\"attr_name_id\":2,\"attr_value_id\":" + brandId + "},";

            } else {
                // 添加商品的品牌
                List<Aliexpress.ValueVo> valueList = aliexpressCategoryServiceImpl.getBrandById(sellerStoreProduct.getCategoryId(),
                        storeId);
                if (valueList == null || valueList.size() == 0)
                    return;
                Aliexpress.ValueVo valueVo = valueList.get(0);
                s = "[{\"attr_name\":\"" + valueVo.getAttr_value() + "\",\"attr_name_id\":2,\"attr_value_id\":"
                        + valueVo.getAttr_value_id() + "},";
            }
            String customAttributes = sellerStoreProduct.getCustomAttributes();
            //0706 速卖通新增 必填属性 高关注化学物质	Hign-concerned Chemical
            String customAttributesOne = null;
            if (!customAttributes.contains("400000603")) {
                 customAttributesOne = customAttributes.replaceFirst("\\[", "[{\"attr_name_id\":400000603,\"attr_name\":\"Hign-concerned Chemical\",\"attr_value_id\":23399591357,\"attr_value\":null},");
                //填充品牌至商品属性
            }
            String customAttributesTwo = customAttributesOne.replaceFirst("\\[", s);
            sellerStoreProduct.setCustomAttributes(customAttributesTwo);

            // 同步运费模板
            if (erpSellerStoreProductExpand.getIsAutoMate() != null
                    && erpSellerStoreProductExpand.getIsAutoMate().equals(1)) { // 自动匹配运费模板
                //判断是否运费模版超过60国
                String absoluteQuoteMapString = (String) absoluteQuoteMap.get("absoluteQuoteMapStr");
                if (ObjectUtils.isNull(absoluteQuoteMapString)) {
                    return;
                }
                // 获取系统预制的运费模板标识
                Integer settingFreightTemplateId = productExpandVo.getTemplateId();
                String mbName = null;
                JSONArray jsonArray = JSONArray.parseArray(absoluteQuoteMapString);
                if (jsonArray.size() > 60) {
//                String mbName = dictService.getDictValue("erp_freight_template", settingFreightTemplateId + "");
                    R<Object> mbNameObject = remoteDictDataService.getDictValue("erp_freight_64_template", settingFreightTemplateId + "");
                    System.out.println(mbNameObject.getData());
                    mbName = mbNameObject.getData().toString();
                } else {
                    R<Object> mbNameObject = remoteDictDataService.getDictValue("erp_freight_template", settingFreightTemplateId + "");
                    System.out.println(mbNameObject.getData());
                    mbName = mbNameObject.getData().toString();
                }

                // 判断用哪个运费模板
                if (StringUtils.isEmpty(mbName)) { // 没有模板发布失败
                    erpSellerStoreProductExpand.setProductStatusType("-2");
                    erpSellerStoreProductExpand.setStatus(3);
                    erpSellerStoreProductExpand.setRemark("没有匹配的模板");
                }
                // 根据店铺id和固定模板名字获取运费模板id
                R<Object> freightTemplateObject = remoteSellerStoreFreightTemplateService.getFreightTemplateOneByStoreIdAndName(storeId, mbName);
                String toJSONString = JSONObject.toJSONString(freightTemplateObject.getData());
                ErpSellerStoreFreightTemplate freightTemplate = JSONObject.parseObject(toJSONString, ErpSellerStoreFreightTemplate.class);

                if (freightTemplate == null) { // 没有模板，先同步一下，防止没有同步发布失败
                    remoteSellerStoreFreightTemplateService.getSellerStoreFreightTemplate(storeId);
                    //再获取一次
                    freightTemplateObject = remoteSellerStoreFreightTemplateService.getFreightTemplateOneByStoreIdAndName(storeId, mbName);
                    toJSONString = JSONObject.toJSONString(freightTemplateObject.getData());
                    freightTemplate = JSONObject.parseObject(toJSONString, ErpSellerStoreFreightTemplate.class);

                    if (freightTemplate == null) { // 同步了还是没有，发布失败
                        erpSellerStoreProductExpand.setProductStatusType("-2");
                        erpSellerStoreProductExpand.setStatus(3);
                        erpSellerStoreProductExpand.setRemark("没有匹配的模板");
                    }
                }
                if (freightTemplate != null)
                    erpSellerStoreProductExpand.setFreightTemplateId(freightTemplate.getTemplateId()); // 运费模板
            }

            baseMapper.insert(sellerStoreProduct);

            // 获取商品sku属性
            String skuProperty = productExpandVo.getSkuProperty();
            List<Dict> skuPropertyList = JsonUtils.parseArrayMap(skuProperty);

            // 创建属性对应map
            Map<String, String> skuPropertyMap = new HashMap<>();
            for (Dict dict : skuPropertyList) {
                List<Map<String, Object>> propertyList = (List<Map<String, Object>>) dict.get("list");
                for (Map<String, Object> propertyMap : propertyList) {
                    skuPropertyMap.put(dict.getStr("value") + ":" + propertyMap.get("value"),
                            propertyMap.get("name") + "");
                }
            }

            // 保存店铺在线商品sku
            for (ErpSellerProductSkuVo vo : productVoSkus) {
                ErpSellerStoreProductSku erpSellerStoreProductSku = new ErpSellerStoreProductSku();
                BeanUtils.copyProperties(vo, erpSellerStoreProductSku);
                erpSellerStoreProductSku.setId(null);
                erpSellerStoreProductSku.setSellerStoreProductId(sellerStoreProduct.getId());
                erpSellerStoreProductSku.setCreateTime(null);
                erpSellerStoreProductSku.setUpdateTime(null);
                erpSellerStoreProductSku.setCreateBy(erpSellerProduct.getSellerId() + "");
                erpSellerStoreProductSku.setUpdateBy(erpSellerProduct.getSellerId() + "");
                if (stock != null) {
                    erpSellerStoreProductSku.setSkuStock(stock);
                } else {
                    Long skuStock = erpSellerStoreProductSku.getSkuStock();
                    if (skuStock == null)
                        erpSellerStoreProductSku.setSkuStock(2999l);
                }

                BigDecimal skuPrice = new BigDecimal(vo.getSkuPrice());
                BigDecimal readjustPrices = (BigDecimal) absoluteQuoteMap.get("readjustPrices");
                BigDecimal profitNum = (BigDecimal) absoluteQuoteMap.get("profitNum");

                // 计算价格
                if (erpSellerStoreProductExpand.getPriceAdjustmentMethod().equals("0")) { // 手动
                    if (readjustPrices != null) {
                        skuPrice = skuPrice.multiply(readjustPrices).setScale(2, BigDecimal.ROUND_HALF_UP);
                    }
                } else { // 智能定价
                    skuPrice = (skuPrice.add(profitNum)).multiply(readjustPrices).setScale(2, BigDecimal.ROUND_HALF_UP);
                }
                erpSellerStoreProductSku.setSkuPrice(skuPrice.toString());

                String skuPropertyIds = erpSellerStoreProductSku.getSkuPropertyIds();
                String[] split = skuPropertyIds.split(";");

                // 添加属性
                List<Map<String, Object>> list = new LinkedList<Map<String, Object>>();
                for (int i = 0; i < split.length; i++) {
                    String string2 = split[i];
                    String[] split2 = string2.split(":");
                    Map<String, Object> map = new HashMap<String, Object>();
                    if (i == 0) {
                        map.put("sku_image", erpSellerStoreProductSku.getSkuImage());
                    }
                    map.put("property_value_definition_name", skuPropertyMap.get(string2));
                    map.put("property_value_id", split2[1]);
                    map.put("sku_property_id", split2[0]);
                    list.add(map);

                }

                erpSellerStoreProductSku.setSkuProperty(JsonUtils.toJsonString(list));

                erpSellerStoreProductSkuMapper.insert(erpSellerStoreProductSku);
            }

            // 保存扩展类
//			erpSellerStoreProductExpand.setAbsoluteQuoteMap(productExpandVo.getAbsoluteQuoteMap()); // 设置区域定价
            erpSellerStoreProductExpand.setSellerStoreProductId(sellerStoreProduct.getId());

            erpSellerStoreProductExpand.setAbsoluteQuoteMap((String) absoluteQuoteMap.get("absoluteQuoteMapStr"));

            // 当状态是null时，设置状态为等待发布，不为null，代表前面设置的有问题不能发布
            if (erpSellerStoreProductExpand.getStatus() == null) {
                erpSellerStoreProductExpand.setProductStatusType("-1"); // 等待发布
                erpSellerStoreProductExpand.setStatus(0); // 等待发布
            }
            erpSellerStoreProductExpand.setCreateBy(erpSellerProduct.getSellerId() + "");
            erpSellerStoreProductExpand.setUpdateBy(erpSellerProduct.getSellerId() + "");

            // 设置系统预制运费模板标识，是否自动匹配运费模板，由前端传过来
            erpSellerStoreProductExpand.setSettingFreightTemplateId(productExpandVo.getTemplateId());

            // 查看运费模板是否有多个发货地
            if (ObjectUtils.isNotNull(erpSellerStoreProductExpand.getFreightTemplateId())) {
                R<Object> freightTemplateLogisticsCompany = remoteSellerStoreFreightTemplateService
                        .getFreightTemplateLogisticsCompany(erpSellerStoreProductExpand.getFreightTemplateId(), storeId);
                if (freightTemplateLogisticsCompany.getCode() == 200) {
                    List<String> dataList = (List<String>) freightTemplateLogisticsCompany.getData();
                    if (ObjectUtils.isNotEmpty(dataList)) {
                        erpSellerStoreProductExpand.setOverseasWarehouse(String.join(",", dataList));
                    }
                }
            }

            erpSellerStoreProductExpandMapper.insert(erpSellerStoreProductExpand);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException("发布失败，商品信息有误");
        }

        // 调用接口发布到速卖通
        // iAeProductService.disposeProductData(sellerProductId,storeId);
    }

    /**
     * 全托管上品准备阶段
     *
     * @param sellerProductId
     * @param storeId
     * @param stock
     * @param brandId
     * @param templateld
     * @return
     */

    @Override
    public R<Object> publishChoiceProduct(Long sellerProductId, Long storeId, Long stock, String brandId, String templateld) {
//        try {
        // 获取个人产品库的商品
        ErpSellerProduct erpSellerProduct = erpSellerProductMapper.selectById(sellerProductId);
        if (erpSellerProduct == null) {
            return R.fail("未查找到个人产品库中信息");
        }

        // 获取个人产品库的商品sku
        List<ErpSellerProductSkuVo> productVoSkus = erpSellerProductSkuMapper
                .selectVoList(new LambdaQueryWrapper<ErpSellerProductSku>()
                        .eq(ErpSellerProductSku::getSellerProductId, sellerProductId));

        // 获取个人产品库的商品扩展表
        ErpSellerProductExpandVo productExpandVo = erpSellerProductExpandMapper
                .selectVoOne(new LambdaQueryWrapper<ErpSellerProductExpand>()
                        .eq(ErpSellerProductExpand::getSellerProductId, sellerProductId));

        // 修改商品价格
//            Map<String, Object> absoluteQuoteMap = countPrice(productExpandVo.getAbsoluteQuoteMap(),
//                    erpSellerStoreProductExpand.getPriceAdjustmentMethod(),
//                    erpSellerStoreProductExpand.getReadjustPricesType(),
//                    erpSellerStoreProductExpand.getReadjustPrices()
//                    , erpSellerStoreProductExpand.getTemplateId(),
//                    erpSellerProduct.getProductPrice());
//            if (Objects.isNull(absoluteQuoteMap)) {
//                return R.fail("调价失败");
//            }

        // 保存到店铺在线商品
        ErpSellerStoreProduct sellerStoreProduct = new ErpSellerStoreProduct();
        BeanUtils.copyProperties(erpSellerProduct, sellerStoreProduct);
        sellerStoreProduct.setId(null);
        sellerStoreProduct.setSellerProductId(sellerProductId);
        sellerStoreProduct.setStoreId(storeId);
        sellerStoreProduct.setCreateTime(null);
        sellerStoreProduct.setUpdateTime(null);
        sellerStoreProduct.setCreateBy(erpSellerProduct.getSellerId() + "");
        sellerStoreProduct.setUpdateBy(erpSellerProduct.getSellerId() + "");
//            sellerStoreProduct.setProductPrice((String) absoluteQuoteMap.get("productPrice"));


        ErpSellerStoreProductExpand erpSellerStoreProductExpand = new ErpSellerStoreProductExpand();

        String s = "";
        if (StringUtils.isNotEmpty(brandId)) {
            Boolean bool = true;
            // 判断是否有这个品牌
            List<Aliexpress.ValueVo> valueList = aliexpressCategoryServiceImpl.getBrandById(sellerStoreProduct.getCategoryId(),
                    storeId);
            if (valueList == null || valueList.size() == 0) {
                erpSellerStoreProductExpand.setProductStatusType("-2");
                erpSellerStoreProductExpand.setStatus(3);
                erpSellerStoreProductExpand.setRemark("没有匹配的品牌");
            } else {
                for (Aliexpress.ValueVo valueVo : valueList) {
                    if (valueVo.getAttr_value_id().toString().equals(brandId))
                        bool = false;
                }

                if (bool) {
                    Aliexpress.ValueVo valueVo = valueList.get(0);
                    brandId = valueVo.getAttr_value_id().toString();
                }
            }

            s = "[{\"attr_name\":\"\",\"attr_name_id\":2,\"attr_value_id\":" + brandId + "},";

        } else {
            // 添加商品的品牌
            List<Aliexpress.ValueVo> valueList = aliexpressCategoryServiceImpl.getBrandById(sellerStoreProduct.getCategoryId(),
                    storeId);
            if (valueList == null || valueList.size() == 0)
                return R.fail("没有品牌可用");
            Aliexpress.ValueVo valueVo = valueList.get(0);
            s = "[{\"attr_name\":\"" + valueVo.getAttr_value() + "\",\"attr_name_id\":2,\"attr_value_id\":"
                    + valueVo.getAttr_value_id() + "},";
        }
        String customAttributes = sellerStoreProduct.getCustomAttributes();
        customAttributes = customAttributes.replaceFirst("\\[", s);
        sellerStoreProduct.setCustomAttributes(customAttributes);

        // 获取商品sku属性
        String skuProperty = productExpandVo.getSkuProperty();
        List<Dict> skuPropertyList = JsonUtils.parseArrayMap(skuProperty);

        // 创建属性对应map
        Map<String, String> skuPropertyMap = new HashMap<>();
        for (Dict dict : skuPropertyList) {
            List<Map<String, Object>> propertyList = (List<Map<String, Object>>) dict.get("list");
            for (Map<String, Object> propertyMap : propertyList) {
                skuPropertyMap.put(dict.getStr("value") + ":" + propertyMap.get("value"),
                        propertyMap.get("name") + "");
            }
        }

        // 保存店铺在线商品sku
        List<ErpSellerStoreProductSku> skuList = new ArrayList<>();
        for (ErpSellerProductSkuVo vo : productVoSkus) {
            ErpSellerStoreProductSku erpSellerStoreProductSku = new ErpSellerStoreProductSku();
            BeanUtils.copyProperties(vo, erpSellerStoreProductSku);
            erpSellerStoreProductSku.setId(null);
            erpSellerStoreProductSku.setSellerStoreProductId(sellerStoreProduct.getId());
            erpSellerStoreProductSku.setCreateTime(null);
            erpSellerStoreProductSku.setUpdateTime(null);
            erpSellerStoreProductSku.setCreateBy(erpSellerProduct.getSellerId() + "");
            erpSellerStoreProductSku.setUpdateBy(erpSellerProduct.getSellerId() + "");
            if (stock != null) {
                erpSellerStoreProductSku.setSkuStock(stock);
            } else {
                Long skuStock = erpSellerStoreProductSku.getSkuStock();
                if (skuStock == null)
                    erpSellerStoreProductSku.setSkuStock(2999l);
            }

            BigDecimal skuPrice = new BigDecimal(vo.getSkuPrice());
//                BigDecimal readjustPrices = (BigDecimal) absoluteQuoteMap.get("readjustPrices");
//                BigDecimal profitNum = (BigDecimal) absoluteQuoteMap.get("profitNum");

//                // 计算价格
//                if (erpSellerStoreProductExpand.getPriceAdjustmentMethod().equals("0")) { // 手动
//                    if (readjustPrices != null) {
//                        skuPrice = skuPrice.multiply(readjustPrices).setScale(2, BigDecimal.ROUND_HALF_UP);
//                    }
//                } else { // 智能定价
//                    skuPrice = (skuPrice.add(profitNum)).multiply(readjustPrices).setScale(2, BigDecimal.ROUND_HALF_UP);
//                }
            erpSellerStoreProductSku.setSkuPrice(skuPrice.toString());

            String skuPropertyIds = erpSellerStoreProductSku.getSkuPropertyIds();
            String[] split = skuPropertyIds.split(";");

            // 添加属性
            List<Map<String, Object>> list = new LinkedList<Map<String, Object>>();
            for (int i = 0; i < split.length; i++) {
                String string2 = split[i];
                String[] split2 = string2.split(":");
                Map<String, Object> map = new HashMap<String, Object>();
                if (i == 0) {
                    map.put("sku_image", erpSellerStoreProductSku.getSkuImage());
                }
                map.put("property_value_definition_name", skuPropertyMap.get(string2));
                map.put("property_value_id", split2[1]);
                map.put("sku_property_id", split2[0]);
                list.add(map);

            }
            erpSellerStoreProductSku.setSkuProperty(JsonUtils.toJsonString(list));
            skuList.add(erpSellerStoreProductSku);
        }

        // 保存扩展类
        erpSellerStoreProductExpand.setSellerStoreProductId(sellerStoreProduct.getId());

//            erpSellerStoreProductExpand.setAbsoluteQuoteMap((String) absoluteQuoteMap.get("absoluteQuoteMapStr"));

        // 当状态是null时，设置状态为等待发布，不为null，代表前面设置的有问题不能发布
        if (erpSellerStoreProductExpand.getStatus() == null) {
            erpSellerStoreProductExpand.setProductStatusType("-1"); // 等待发布
            erpSellerStoreProductExpand.setStatus(0); // 等待发布
        }
        erpSellerStoreProductExpand.setCreateBy(erpSellerProduct.getSellerId() + "");
        erpSellerStoreProductExpand.setUpdateBy(erpSellerProduct.getSellerId() + "");


        JSONObject productInfoObject = new JSONObject();

        productInfoObject.put("erpSellerStoreProduct", sellerStoreProduct);
        productInfoObject.put("erpSellerStoreProductExpand", erpSellerStoreProductExpand);
        productInfoObject.put("erpSellerStoreProductSku", skuList);

        productInfoObject.put("erpSellerProduct", erpSellerProduct);
        productInfoObject.put("erpSellerProductExpand", productExpandVo);
        productInfoObject.put("erpSellerProductSku", productVoSkus);


        return publishAeChoiceProduct(productInfoObject);

//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//            throw new RuntimeException("发布失败，商品信息有误");
//        }
    }


    /**
     * 全托管店铺发布到速卖通
     */
    public R<Object> publishAeChoiceProduct(JSONObject productInfoObject) {
        System.out.println("~~~~~~~~~~~~~~~~~~~~~");
        System.out.println(productInfoObject.getJSONObject("erpSellerStoreProduct"));
        System.out.println("~~~~~~~~~~~~~~~~~~~~~");

        ErpSellerStoreProduct erpSellerStoreProduct = JSONObject.parseObject(productInfoObject.getJSONObject("erpSellerStoreProduct").toJSONString(), ErpSellerStoreProduct.class);
        ErpSellerStoreProductExpand erpSellerStoreProductExpand = JSONObject.parseObject(productInfoObject.getJSONObject("erpSellerStoreProductExpand").toJSONString(), ErpSellerStoreProductExpand.class);
        List<ErpSellerStoreProductSku> erpSellerStoreProductSkuList = JSONArray.parseArray(productInfoObject.getJSONArray("erpSellerStoreProductSku").toJSONString(), ErpSellerStoreProductSku.class);

        ErpSellerProduct erpSellerProduct = JSONObject.parseObject(productInfoObject.getJSONObject("erpSellerProduct").toJSONString(), ErpSellerProduct.class);
        ErpSellerProductExpand erpSellerProductExpand = JSONObject.parseObject(productInfoObject.getJSONObject("erpSellerProductExpand").toJSONString(), ErpSellerProductExpand.class);
        List<ErpSellerProductSku> erpSellerProductSkuList = JSONArray.parseArray(productInfoObject.getJSONArray("erpSellerProductSku").toJSONString(), ErpSellerProductSku.class);

        ErpCollectProduct erpCollectProduct = erpCollectProductMapper.selectById(erpSellerStoreProduct.getCollectProductId());
        ErpCollectProductExpand erpCollectProductExpand = collectProductExpandMapper.selectByCollectProductId(erpSellerStoreProduct.getCollectProductId());
        List<ErpCollectProductSku> erpCollectProductSkuList = erpCollectProductSkuMapper.selectList(
                new LambdaQueryWrapper<ErpCollectProductSku>().eq(ErpCollectProductSku::getCollectProductId, erpSellerStoreProduct.getCollectProductId())
        );


        JSONObject dto = new JSONObject();
        //渠道seller id （可以在这个API中查询：global.seller.relation.query）， 请使用 business_type = ONE_STOP_SERVICE 的全托管店铺 channel_seller_id
        dto.put("channel_seller_id", "6000122591");
        //渠道（可以在这个API中查询：global.seller.relation.query）
        dto.put("channel", "AE_GLOBAL");
        // 版本号。不传默认是1。 1代表商货融合之前的版本，不能自动创建货品； 2 代表商货融合的版本，需要做货品信息的参数校验，发品成功自动商货绑定。
        dto.put("version", 1);

        //具体商品信息
        JSONObject productDto = new JSONObject();
        dto.put("one_stop_service_product_dto", productDto);

        /** 媒体信息 **/
        JSONObject multimediaDto = new JSONObject();
        //视频信息 暂不上传
        //multimediaDto.put("video_list", null);
        //营销图列表
        JSONArray marketImagesList = new JSONArray();
        JSONObject marketImages = new JSONObject();
        marketImages.put("url", erpSellerStoreProduct.getMarketing());
        marketImages.put("image_type", 1);
        marketImagesList.add(marketImages);
        JSONObject whiteImages = new JSONObject();
        whiteImages.put("url", erpSellerStoreProduct.getWhite());
        whiteImages.put("image_type", 2);
        marketImagesList.add(whiteImages);
        multimediaDto.put("market_image_list", marketImagesList);

        //商品主图列表
        String imageURLs = erpSellerStoreProduct.getImageURLs();
        String imageNewUrl = new String();
        List<String> imageNewList = Arrays.asList(imageURLs.split(";"));
        if (imageNewList.size() > 2) {
            //有两张以上时调序
            //获取第一张
            String imageOne = imageNewList.get(0);
            //获取除第一张的其他List
            List<String> otherElements = imageNewList.subList(1, imageNewList.size());
            Collections.shuffle(otherElements);
            imageNewUrl = imageOne + ";" + StringUtils.join(otherElements, ";");
            System.out.println(imageNewUrl);
        }
        multimediaDto.put("main_image_list", imageNewUrl);
        dto.put("multimedia", multimediaDto);
        /** 媒体信息 **/


        /** 包裹信息 **/
        JSONObject packageDto = new JSONObject();
        //每包的数量
        packageDto.put("lot_num", erpCollectProductExpand.getLotNum());
        //产品的单位
//        packageDto.put("product_unit", null);
        //打包销售: true 非打包销售:false
        packageDto.put("package_type", erpCollectProductExpand.getPackageType());
        dto.put("package_dto", packageDto);
        /** 包裹信息 **/

        /** 扩展信息 **/
        JSONObject productExtDto = new JSONObject();
        //欧盟责任人id，需要调用查询欧盟责任人列表接口：aliexpress.category.eu.responsible.persons.list，获取对应的欧盟责任人列表
        String msrEuId = getEUResponsiblePersonByCategoryId(
                erpCollectProduct.getCategoryId(), erpSellerStoreProduct.getStoreId(), 1);
        if (msrEuId != null) {
            productExtDto.put("msr_eu_id", msrEuId);
        }
        //全托管商品备货类型， 仓发：0 ； 即时补货（JIT）：1 ； 海外备仓：2 。
        productExtDto.put("product_type", 1);
        dto.put("product_ext_dto", productExtDto);
        /** 扩展信息 **/

        /** 商品基本信息 **/
        JSONObject productInfoDto = new JSONObject();
        //商品标题
        JSONObject subject = new JSONObject();
        subject.put("locale", "en_US");
        subject.put("value", erpSellerStoreProduct.getSubject());
        JSONArray subjectList = new JSONArray();
        subjectList.add(subject);
        productInfoDto.put("subject_list", subjectList);

        //商品原发语种：en_US
        productInfoDto.put("locale", "en_US");
        //货币单位。如果不提供该值信息，则默认为"USD"；非俄罗斯卖家这个属性值可以不提供。对于俄罗斯海外卖家，该单位值必须提供，如: "RUB"。
        productInfoDto.put("currency_code", "USD");
        //类目id
        productInfoDto.put("category_id", erpSellerStoreProduct.getCategoryId());
        dto.put("product_info_dto", productInfoDto);
        /** 商品基本信息 **/

        /** 详描列表 **/
        JSONArray detailSourceList = new JSONArray();
        JSONObject detailSource = new JSONObject();
        String makeDetail = makeDetail(erpSellerStoreProduct.getDetail(), erpSellerStoreProduct.getDetailImg());
        detailSource.put("mobile_detail", makeDetail);
        detailSource.put("web_detail", makeDetail);
        detailSource.put("locale", "en_US");
        detailSourceList.add(detailSource);
        dto.put("detail_source_list", detailSourceList);
        /** 详描列表 **/

        /** 商品属性列表 **/
        JSONArray productPropertyList = JSONArray.parseArray(erpSellerStoreProduct.getCustomAttributes());
        dto.put("product_property_list", productPropertyList);
        /** 商品属性列表 **/


        /** 商品sku列表 **/
        JSONArray aeopAeProductSkus = new JSONArray();
        Map<String, ErpCollectProductSku> skuMap = new HashMap<>();
        for (ErpCollectProductSku sku : erpCollectProductSkuList) {
            skuMap.put(sku.getSkuCode(), sku);
        }
        for (ErpSellerStoreProductSku productSku : erpSellerStoreProductSkuList) {
            JSONObject sku = new JSONObject();
            sku.put("sku_code", productSku.getSkuCode());
//            sku.put("sku_discount_price",productSku.getSkuDiscountPrice());
            sku.put("currency_code", "USD");
            // 换算价格
            //如果店铺是USD账户，则进行换算，如果不是则不换算
            BigDecimal skuConversionPrice = BigDecimal.valueOf(0);
//            if (storeExtendSel.getQuotationCurrency().equals("USD")) {
//                skuConversionPrice = BigDecimal.valueOf(Double.valueOf(productSku.getSkuPrice()))
//                        .multiply(BigDecimal.valueOf(100)).divide(newUsdExchange, BigDecimal.ROUND_CEILING);
//                sku.put("sku_price", skuConversionPrice.toString());
//            } else {
            sku.put("supply_price", productSku.getSkuPrice());
//            }
            ErpCollectProductSku collectSku = (ErpCollectProductSku) skuMap.get(productSku.getSkuCode());
            if (ObjectUtils.isNull(collectSku)) {
                continue;
            }

            sku.put("package_weight", collectSku.getSkuWeight().toString());
            sku.put("package_height", collectSku.getSkuHeight().intValue());
            sku.put("package_width", collectSku.getSkuWidth().intValue());
            sku.put("package_length", collectSku.getSkuLength().intValue());
            JSONArray skuPropertyArray = JSONArray.parseArray(productSku.getSkuProperty());
            sku.put("sku_property_value", skuPropertyArray);
            aeopAeProductSkus.add(sku);
        }
        dto.put("product_sku_list", aeopAeProductSkus);
        /** 商品sku列表 **/

        return R.ok(dto);
    }


    /**
     * 商品详描处理
     *
     * @param detail
     * @param imgUrls
     * @return
     */
    public String makeDetail(String detail, String imgUrls) {
        Map<String, Object> map = new HashMap<>();
        map.put("version", "2.0.0");
        Map<String, Object> map1 = new LinkedMap<String, Object>();
        map1.put("type", "text-image");

        // 文本
        List<Object> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(detail)) {
            String[] split = detail.split("\n");
            for (String string : split) {
                Map<String, Object> map2 = new HashMap<String, Object>();
                map2.put("content", string);
                map2.put("class", "body");
                list.add(map2);
            }
        }

        // 图片
        List<Object> list2 = new LinkedList<>();
        String[] split2 = imgUrls.split(";");
        for (String string : split2) {
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("url", string);
            map2.put("style", new HashMap<>());
            list2.add(map2);
        }

        if (list != null && list.size() != 0)
            map1.put("texts", list);
        if (list2 != null && list2.size() != 0)
            map1.put("images", list2);
        List<Object> resList = new ArrayList<Object>();
        resList.add(map1);
        map.put("moduleList", resList);
        return JsonUtils.toJsonString(map);
    }

    public String getEUResponsiblePersonByCategoryId(Long categoryId, Long sellerStoreId, Integer type) {
        // sellerStoreId为当前登录账号id

        // 判断该店铺是否存在并已授权
        R<Object> objectR = remoteSellerStoreService.getSellerStoreInfoById(sellerStoreId);
        String toJSONString = JSONObject.toJSONString(objectR.getData());
        ErpSellerStoreEmpower erpSellerStoreEmpower = JSONObject.parseObject(toJSONString, ErpSellerStoreEmpower.class);
        if (erpSellerStoreEmpower == null || erpSellerStoreEmpower.getIsEmpower().equals("0")) {
            return null;
        }
        // 获取该店铺该类目下的信息是否存在
        if (type == 1) {
            //测试正常
            ErpSellerStoreEuResponsiblePerson erpSellerStoreEuResponsiblePerson = erpSellerStoreEuResponsiblePersonMapper
                    .selectOne(new LambdaQueryWrapper<ErpSellerStoreEuResponsiblePerson>()
                            .eq(ErpSellerStoreEuResponsiblePerson::getCategoryId, categoryId)
                            .eq(ErpSellerStoreEuResponsiblePerson::getSellerStoreId, sellerStoreId)
                            .last("limit 1"));
            if (erpSellerStoreEuResponsiblePerson != null) {
                // 若存在，返回该值
                return erpSellerStoreEuResponsiblePerson.getMsrEuId().toString();
            } else {
                // 若不存在，调用AE接口，该类目下的欧盟负责人

                return getEUResponsiblePersonFromAe(categoryId, sellerStoreId);
            }
        } else {
            return getEUResponsiblePersonFromAe(categoryId, sellerStoreId);
        }
    }


    //调用AE接口获取该类目下的欧盟负责人
    public String getEUResponsiblePersonFromAe(Long categoryId, Long sellerStoreId) {
        R<Object> objectR = remoteAeProductService.getEUResponsiblePersonFromAeInnerAuth(categoryId, sellerStoreId);
//        ResponseEntity<String> forEntity = restTemplate
//                .getForEntity(aeConfig.getEndpoint() + "/erp/erpProduct/getEUResponsiblePersonFromAe?categoryId="
//                        + categoryId + "&sellerId=" + sellerStoreId, String.class);
//        String body = (String) forEntity.getBody();
        String body = JSONObject.toJSONString(objectR.getData());
        Dict dict = JsonUtils.parseMap(body);
        if (Integer.valueOf(dict.get("code").toString()) == 500) {
            return null;
        }
        // 存储数据
        ErpSellerStoreEuResponsiblePerson erpSellerStoreEuResponsiblePerson =
                erpSellerStoreEuResponsiblePersonMapper.selectOne(
                        new LambdaQueryWrapper<ErpSellerStoreEuResponsiblePerson>()
                                .eq(ErpSellerStoreEuResponsiblePerson::getSellerStoreId, sellerStoreId)
                                .eq(ErpSellerStoreEuResponsiblePerson::getCategoryId, categoryId)
                );
        if (erpSellerStoreEuResponsiblePerson == null) {
            erpSellerStoreEuResponsiblePerson = new ErpSellerStoreEuResponsiblePerson();
        }
        erpSellerStoreEuResponsiblePerson.setSellerStoreId(sellerStoreId);
        erpSellerStoreEuResponsiblePerson.setCategoryId(categoryId);
        erpSellerStoreEuResponsiblePerson.setSupport(dict.get("support").toString());
        Boolean flag = false;
        if (erpSellerStoreEuResponsiblePerson.getSupport().equals("true")) {
            erpSellerStoreEuResponsiblePerson.setMsrEuId(Long.valueOf(dict.get("msr_eu_id").toString()));
            erpSellerStoreEuResponsiblePerson.setName(dict.get("name").toString());
            flag = true;
        } else {
            erpSellerStoreEuResponsiblePerson.setMsrEuId(Long.valueOf(-2));
            erpSellerStoreEuResponsiblePerson.setName("暂无欧盟负责人");
        }
        if (erpSellerStoreEuResponsiblePersonMapper.insertOrUpdate(erpSellerStoreEuResponsiblePerson)) {
            if (flag) {
                return erpSellerStoreEuResponsiblePerson.getMsrEuId().toString();
            } else {
                return null;
            }
        } else {
            return null;
        }
    }



}
